package com.hn658.base.message.appinfo.dao.redis.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import com.hn658.base.message.appinfo.dao.redis.IAppInfoRedisDAO;
import com.hn658.base.message.appinfo.entity.AppInfoEO;
import com.hn658.base.message.common.utils.RedisKeyHelper;
import com.hn658.framework.dataaccess.redis.AbstractRedisDAO;
import com.hn658.framework.shared.utils.JsonMapper;

/**
 * 应用Redis DAO 实现类
 * 
 * @author ztjie
 * 
 */
@Repository
public class AppInfoRedisDAOImpl extends AbstractRedisDAO<AppInfoEO>
		implements IAppInfoRedisDAO {
	@Autowired
	@Qualifier("redisTemplate")
	@Override
	public void setTemplate(StringRedisTemplate template) {
		super.template = template;
	};
	
	JsonMapper jsonMapper = JsonMapper.nonEmptyMapper();
	
	@Override
	public AppInfoEO findAppById(Long id) {
		if(id==null){
			return null;
		}
		String appInfoJson = valueOps.get(RedisKeyHelper.appKey(id.toString()));
		AppInfoEO app = jsonMapper.fromJson(appInfoJson, AppInfoEO.class);
        return app;
	}

	@Override
	public AppInfoEO findAppByAppId(String appKey) {
		// 先获取clientId对应的Uid
		String id = findIdByAppId(appKey);
		if(StringUtils.isEmpty(id)){
			return null;
		}

		// 从Redis中获取对应uid的AppInfo
		return this.findAppById(Long.valueOf(id));
	}

	@Override
	public void saveApp(AppInfoEO appInfo) {
		if(appInfo == null){
			return;
		}
		
        if (StringUtils.isNotBlank(appInfo.getId().toString())) {
            // 设置appId对应的id
            valueOps.set(RedisKeyHelper.appKey(appInfo.getAppId().toString()),
            		appInfo.getId().toString());
            String appInfoJson = jsonMapper.toJson(appInfo);
            valueOps.set(RedisKeyHelper.appInfoId(appInfo.getId().toString()), appInfoJson);
        }
        
	}
	
	/**
	 * 根据appId查找id
	 * @param appId
	 * @return
	 */
	private String findIdByAppId(String appId) {
		return valueOps.get(RedisKeyHelper.appKey(appId));
	}

	/**
	 * 
	 * <p>删除关联的redis数据</p> 
	 * @author ztjie
	 * @date 2015-11-8 下午7:49:51
	 * @param id 
	 * @see com.hn658.user.appinfo.dao.redis.IAppInfoRedisDAO#deleteApp(java.lang.Long)
	 */
	@Override
	public void deleteApp(Long id) {
		this.template.delete(RedisKeyHelper.appInfoId(id.toString()));
		AppInfoEO appInfo = this.findAppById(id);
		if(appInfo!=null){
			this.template.delete(RedisKeyHelper.appKey(appInfo.getAppId().toString()));			
		}
	}
}
